<template>  
    
    <div class="shopCart">
        <HeaderBar title="购物车" :right ="optionInfo" @rightClick="rightClick"/>
        <LoginPop ref="loginPop" @onLoginSuccess="onOnLoginSuccess"/>
        <div class="listContainer">
            <upLoadDownRefresh 
                @refresh="refresh"
                :maxDistance="300"
                :triggerDistance="100"
                >
                <div class="productList" v-if="shopCartList.length>0">
                    <div class="product" v-for="item in shopCartList" :key="item.Id">
                        <a-checkbox :checked="judgeIsChecked(item)"  @change="onChange(item)">
                        </a-checkbox>
                        <div class="productInfo">
                            <div class="productName" style=""> {{item.Name}}</div>
                            <span style="color: chocolate;margin-left: 10px;width: 34px;" v-if="editStatus===false"> x {{ item.Qty }}</span>
                            <a-input class="editInput" v-if="editStatus===true" @blur="updateShopCart(item)" style="width: 50px;margin-left: 20px;" type="number" size="small" placeholder="数量" v-model="item.Qty"></a-input>
                        </div>
                        <div style="color: #950000;font-weight: 600; font-size: large;"> {{ item.SubTotal }}</div>
                    </div>
                </div>
                <div v-else class="empty">
                    空空如也，快去选购商品吧~
                </div>
            </upLoadDownRefresh>
            <div class="footer" v-if="shopCartList.length>0">
                <a-checkbox :checked="selectAllChecked"  @change="allChecked">{{ allselectString }}
                </a-checkbox>
                <div v-if="editStatus===false" style="display: flex; align-items: center;">
                    <div class="totalPrice" style=" text-align: right;flex: 1;padding-right: 20px;">总价： ￥{{ selectTotalPrice }}</div>
                    <div class="order" @click.prevent="createOrder">立即下单</div>
                </div>
                <div v-else @click.prevent="removeShopCart" class="order"> 删除</div>
            </div>
        </div>
    </div>
</template>
<script>
import HeaderBar from '@/components/Header.vue'
import LoginPop from '@/components/popup/LoginPop.vue';
import { getShopingCart,deleteShopingCart,editShopingCart,createOrderInCart } from '@/api/shopcart';
// import {goodsCheckout} from '@/api/product.js';
import { getPaymentMethod } from "@/api/user.js";
export default {
    name:'ShopCartView',
    components:{
        HeaderBar,
        LoginPop
    },
    data(){
        return{
            shopCartList:[],
            visible:false,
            checkedItems:[],
            defaultPayment:'',
            optionInfo:'编辑',
            editStatus:false,
        }
    },
    computed:{
        
        allselectString(){
            return this.selectAllChecked?'取消选择':'选择全部';
        },
        selectAllChecked(){
            return this.checkedItems.length === this.shopCartList.length;
        },
        selectTotalPrice(){
            let total = 0;
            this.checkedItems.forEach(item=>{
                //console.log(item)
                
                total += parseFloat(item.SubTotal.substring(1).replace(/,/g,"") );
            })
            return total.toFixed(2);
        }
    },
    // mounted(){
    //     getShopingCart().then(res=>{
    //         //console.log(res);
    //         if(res.data.length>0){
    //             this.shopCartList = res.data;
    //         }
    //     }).catch(err=>{
    //         //console.log(err);
    //     })
    // },
    methods:{
        removeShopCart(){
            let removeItems = this.checkedItems.map((item)=>{
                //console.log(item)
                return deleteShopingCart({id:item.Id}).then((res)=>{
                    if(res.Code==200){
                        return true;
                    }else{
                        return false
                    }
                }).catch(err=>{
                    console.log(err);
                return false;
            });
            });
            Promise.all(removeItems).then(res=>{
                console.log(res);
                this.checkedItems=[];
                this.refresh()

            }).catch(err=>{
                console.log(err);
            })

        },
        updateShopCart(item){
            //console.log(item)
            item.SubTotal = '￥'+ (parseFloat(item.UnitPrice.substring(1).replace(/,/g,"")) * item.Qty).toFixed(2);
        },
        rightClick(){
            //console.log('right click')
            if(this.optionInfo==='编辑'){
                this.optionInfo='完成',
                this.editStatus=true;
            }else{
                this.optionInfo='编辑',
                this.editStatus=false; 
            }

        },
        createOrder(){
          if(this.checkedItems.length<=0){
            this.$message.info("请选择商品")
          }else{
            // let tGoodsValues=[];
            let checkCallBack = this.checkedItems.map(item=>{
                console.log(item)

                return editShopingCart({
                        Id: item.Id,
                        Quantity: item.Qty,
                        Selected: true
                    }).then(res=>{  
                        if(res.Code==200){
                            return true;
                        }else{
                            return false
                        }
                    }).catch(err=>{
                    console.log(err);
                    return false
                    })
                });
                Promise.all(checkCallBack).then(res=>{
                    console.log(res)
                    let query = {
                        PaymentMethod: this.defaultPayment,
                        Balance: 0,
                        AddressId: 0,
                        Remark: "",
                    }
                    createOrderInCart(query).then(res=>{
                        console.log(res);
                        this.refresh();

                    }).catch(err=>{console.log(err)})
                }).catch(err=>{console.log(err)})

            // for(let i = 0;i<this.checkedItems.length;i++){
            //     let tGoodsValue = {};
            //     tGoodsValue.Sku=this.checkedItems[i].Sku;
            //     tGoodsValue.Qty=this.checkedItems[i].Qty;
            //     tGoodsValues.push(tGoodsValue);
            // }
            // let query = {
            //     PaymentMethod: this.defaultPayment,
            //     Balance: 0,
            //     AddressId: 0,
            //     OrderTotal:this.selectedPrice,
            //     Remark: "",
            //     GoodsValues:tGoodsValues,
            // }
            // goodsCheckout(query).then((res)=>{
            //             if(res.Code==200){
            //                 this.$message.success('下单成功')
            //                 this.refresh();
            //             }else{
            //                 this.$message.error('下单失败')
            //             }
            //         });
            //console.log("tGoodsValues",tGoodsValues)
           
          }
 
        },
        allChecked(e){
            //console.log(e)
            this.selectAllChecked = e.target.checked;
            if(e.target.checked){
                this.allselectString='取消选择'
                this.checkedItems = [...this.shopCartList];
            }else{
                 this.allselectString='选择全部'
                this.checkedItems = [];
            }
        },
        onChange(item){
            //console.log(item)
            this.onItemChecked(item);
        },
        onItemChecked(item){
            //console.log('item checked')
            let finalIndex = -1;
            for(let index =0; index<this.checkedItems.length;index++){
                if(this.checkedItems[index].Id === item.Id){
                    finalIndex = index;
                    break;
                }
            }
            if(finalIndex>-1){
                this.checkedItems.splice(finalIndex,1)
            }else{
                this.checkedItems.push(item)
            }
            //console.log(this.checkedItems)
        },
        
        judgeIsChecked(item){
            let isChecked = false;
            for(let index =0; index<this.checkedItems.length;index++){
                if(this.checkedItems[index].Id === item.Id){
                    isChecked= true;
                }
            }
          return isChecked
        },
        onOnLoginSuccess(){
            //console.log('登录成功，加载数据');
            getShopingCart().then(res=>{
                //console.log(res);
                this.shopCartList = res.Data.Items;
            })
        },
        refresh(done){
            getShopingCart().then(res=>{
                //console.log(res);
                this.shopCartList = res.Data.Items;
                if(done){
                    setTimeout(()=>{
                        done();
                    },1000)
                }
                
            }).catch(err=>{

                console.log(err);

                if(done){
                    setTimeout(()=>{
                        done();
                    },1000)
                }
            })
            
        },
        showModal() {
            this.visible = true;
        },
        handleOk(e) {
            console.log(e);
            this.visible = false;
        },

        openLogin(){
            this.$refs.loginPop.open();
        },
    },
    mounted(){
        if(!localStorage.getItem('userToken')){
            this.$refs.loginPop.open();
        }else{
            getShopingCart().then(res=>{
                // //console.log(res);
                this.shopCartList = res.Data.Items
            })
            getPaymentMethod().then(res=>{
                // //console.log(res);
                this.defaultPayment = res.Data[0].PaymentMethodSystemName;
            })
        }
        
    }
}

</script>
<style scoped>
.shopCart{
    background-color: #950000;
    height: 90%;
    width: 100vw;
    display: flex;
    flex-direction: column;
}
.productInfo{
    
    width: 100%;
    display: flex;
}
.productName{
    margin-left: 20px;
    font-size:medium;
    max-width: 160px;
    text-align: left;
    color: #444;
    font-weight: 600;
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 显示省略号 */
}
.listContainer{
    flex: 1;
    background-color: white;
}
.shopCartContainer{
    width: 100%;
    flex: 1;
    background-color: white;
    overflow-y: scroll;
}
.totalPrice{
    margin-right: 10px;
    font-size: 16px;
    color: #950000;
    font-weight: 600;

}
.order{
    line-height: 50px;
    width: 80px;
    background-color: red;
    font-size: 16px;
    color: white;
}
.productList{
    height: calc(100vh - 172px);
    overflow: auto;
}
.empty{
    text-align: center;
    padding-top: 200px;   
}
.product{
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    padding:0 10px;
    font-size: 16px;
    border-bottom: lightgray solid 1px;
}
::v-deep #scroll-container{
    background-color: white !important;
}
.footer{
 position: fixed;
 width: 100%;
 height: 50px;
 display: flex;
 align-items: center;
 justify-content: space-between;
 padding: 0 0 0  10px;
 bottom: 80px;
 background-color: #ededed;
}
</style>